package com.bear.atlassianmcp.confluence.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.time.Duration;

/**
 * Confluence集成配置类
 * 负责配置Confluence连接参数和HTTP客户端
 */
@Configuration
public class ConfluenceConfig {

    private static final Logger logger = LoggerFactory.getLogger(ConfluenceConfig.class);

    /**
     * 配置RestTemplate用于Confluence API调用
     */
    @Bean("confluenceRestTemplate")
    public RestTemplate confluenceRestTemplate() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout((int) Duration.ofSeconds(30).toMillis());
        factory.setReadTimeout((int) Duration.ofSeconds(60).toMillis());

        RestTemplate restTemplate = new RestTemplate(factory);

        // 添加自定义错误处理器
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
            @Override
            public boolean hasError(ClientHttpResponse response) throws IOException {
                HttpStatus statusCode = HttpStatus.resolve(response.getRawStatusCode());
                if (statusCode != null) {
                    logger.debug("Confluence API response status: {}", statusCode);
                    return statusCode.isError();
                }
                return super.hasError(response);
            }

            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                HttpStatus statusCode = HttpStatus.resolve(response.getRawStatusCode());
                logger.error("Confluence API error - Status: {}, Headers: {}",
                           statusCode, response.getHeaders());
                super.handleError(response);
            }
        });

        return restTemplate;
    }
}
